import {
  createElasticsearchClient,
  ElasticsearchClient,
  ElasticsearchClientProp
} from "$/elasticsearch-client";
import { Url } from "$/entity";

export interface ClientCacheServiceProp {
  adapter: ElasticsearchClientProp["adapter"];
  getUrlById: (id: string) => Promise<Url | null>;
}

export interface ClientCacheServiceResult {
  getClientCache: (id: string) => Promise<ElasticsearchClient>;
  deleteClientCache: (id: string) => void;
}

export const ClientCacheService = (props: ClientCacheServiceProp): ClientCacheServiceResult => {
  const { adapter, getUrlById } = props;

  const clientCacheMap = new Map<string, ElasticsearchClient>();

  async function getClientCache(id: string) {
    const cache = clientCacheMap.get(id);
    if (cache) return cache;
    const url = await getUrlById(id);
    if (!url) return Promise.reject(new Error("连接不存在"));
    const client = createElasticsearchClient({
      ...url,
      adapter: adapter
    });
    clientCacheMap.set(id, client);
    return client;
  }

  function deleteClientCache(id: string) {
    clientCacheMap.delete(id);
  }

  return {
    getClientCache,
    deleteClientCache
  };
};
